$(function() {
    var indexObj = new UserGroupIndex();
    indexObj._init();
});

function UserGroupIndex() {

    var me = this;
    var record;
    var zTree;
    var zTreeNodes, selectedNode;

    this._init = function() {
        bindEvents();

        initTree();

        setValidation();
    };

    function bindEvents() {
        $('#addBtn').on('click', function() {
           
            record = {};
            record.isNew = true;
            var selectedNodes = zTree.getSelectedNodes();
            if (selectedNodes.length > 0) {
                selectedNode = selectedNodes[0];
                console.log('selectedNode');
                console.log(selectedNode);
                record.parentId = selectedNode.id;
                record.parentName = selectedNode.name;
            }
            popupModal();
            fillForm();
        });
        
        $('#editBtn').on('click', function() {
            
            record = {};
            var selectedNodes = zTree.getSelectedNodes();
            if (selectedNodes.length > 0) {
                selectedNode = selectedNodes[0];
                console.log(selectedNode);
                
                popupModal();
            } else {
                alert('请选择一条数据！');
            }
           
        });

        $('#userGroupModal').on('show.bs.modal', function(e) {
            
            if (!record.isNew) {
                // 从后台加载完整的数据
                var url = contextPath + '/userGroup/findById?userGroupId=' + selectedNode.id;
                jsonAjax(url, 'GET', function(data) {
                    record = data;
                    record.parentName = selectedNode.getParentNode() ? selectedNode.getParentNode().name : null;
                    
                    fillForm();
                });
            } else {
                fillForm();
            }
           
            console.log('onshow');
        });

        $('#userGroupModal #saveBtn').on('click', function(e) {
            saveRecord();
        });
        
        $('#deleteBtn').on('click', function(e) {
            var selectedNodes = zTree.getSelectedNodes();
            if (selectedNodes.length > 0) {
                deleteRecord(selectedNodes[0].id);
            } else {
                alert('请选择一条数据！');
            }
        });
    }

    function initTree() {
        var setting = {
            treeNodeKey : 'id', // 在isSimpleData格式下，当前节点id属性
            treeNodeParentKey : 'pId', // 在isSimpleData格式下，当前节点的父节点id属性
            showLine : true, // 是否显示节点间的连线
            checkable : true, // 每个节点上是否显示 CheckBox
            async : {
                enable : true,
                url : contextPath + '/userGroup/getUserGroupTree',
                type : 'GET',
            },
            data : { // 使用简单数据类型
                simpleData : {
                    enable : true
                }
            }
        };
        
        zTree = $.fn.zTree.init($("#tree"), setting);
        console.log(zTree);
    }

    function refreshTree() {
        zTree.reAsyncChildNodes(null, "refresh", false);
    }

    function popupModal() {
        $('#userGroupModal').modal('show');
    }

    function fillForm() {
        console.log(record);
        fillJsForm('#editUserGroupForm', record);
    }

    function setValidation() {
        $('#editUserGroupForm').validate({
            rules : {
                'data.code' : {
                    required : true,
                    maxlength : 20
                },
                'data.name' : {
                    required : true,
                    maxlength : 20
                },
                'data.remark' : {
                    maxlength : 100
                },
            },
            errorElement : "span",
            errorPlacement : function(error, element) {
                error.addClass("help-block");
                if (element.prop("type") === "checkbox") {
                    error.insertAfter(element.parent("label"));
                } else {
                    error.insertAfter(element);
                }
            },
            highlight : function(element, errorClass, validClass) {
                $(element).parents(".col-sm-10").addClass("has-error").removeClass("has-success");
            },
            unhighlight : function(element, errorClass, validClass) {
                $(element).parents(".col-sm-10").addClass("has-success").removeClass("has-error");
            }
        });
    }

    function saveRecord() {
        var valid = $('#editUserGroupForm').valid();
        console.log('validated: ' + valid);

        if (valid) {
            record = $("#editUserGroupForm").jsForm("get");
            console.log(record);
            var json = JSON.stringify(record);

            $.ajax({
                url : contextPath + '/userGroup/save',
                type : 'POST',
                dataType : 'json',
                contentType : 'application/json',
                data : json,
                success : function(data) {
                    record = null;
                    if (data.success) {
                        alert('保存成功');

                        $('#userGroupModal').modal('hide');
                        refreshTree();
                    } else {
                        alert('保存失败: ' + data.errorMessage);
                    }
                }
            });
        }
    }

    function deleteRecord(id) {
        console.log(id);
        if (!confirm('确定删除吗？')) {
            return false;
        } else {
            $.ajax({
                url : contextPath + '/userGroup/delete?id=' + id,
                type : 'DELETE',
                dataType : 'json',
                contentType : 'application/json',
                success : function(data) {
                    if (data.success) {
                        alert('删除成功');
                        refreshTree();
                    } else {
                        alert('保存失败: ' + data.errorMessage);
                    }
                }
            });
            return true;
        }
    }

}